package dsync.SFile;

import java.io.*;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileNotFoundException;

/**
 * Class present file not is directory
 * @author ilya
 * @see Sync_Object 
 */
public class SFile extends File 
	implements Sync_Object<File> {

	private SFile currentFile;
	private static final long serialVersionUID = 1L;
	private Logger slog;
	
	/**
	 * Information on sync write to "SFile.log"
	 * 
	 * @throws SecurityException
	 * @throws IOException
	 */
	
	public SFile(String pathname) throws SecurityException, IOException {
		
		super(pathname);
		
		currentFile = this;
		slog = Logger.getLogger("SFile");
		slog.addHandler(new FileHandler("SFile.log", true));
		
		if(!this.exists() || isDirectory())
			throw new FileNotFoundException(this.getAbsolutePath() + " - file not found");
		
	}
	
	public Date getData() {
		return new Date(this.lastModified());

	}
	/**
	 * 
	 * @param f - file descriptor 
	 * @return time last modified to f in Object "java.util.Date"
	 */
	public Date getData(File f)
	{
		return new Date(f.lastModified());
	}
	
	/**
	 * @param so - file descriptor for sync
	 * @throws IOException if file is directory
	 * @throws FileNotFoundException if file not exists
	 */
	
	public void sync(File so) throws IOException, FileNotFoundException {
		
		if(!so.exists())
		{
			throw new FileNotFoundException();
		}
		
		if(so.isDirectory())
		{
			throw new IOException("file is directory");
			
		}
		
		if(currentFile.getData().getTime() == new Date(so.lastModified()).getTime()){
			slog.log(Level.INFO, so.getAbsolutePath() + ": " + 
					"update no required\n");
		}
		else
		{
			if(currentFile.getData().getTime() > new Date(so.lastModified()).getTime())
			{
				slog.log(Level.INFO, this.getAbsolutePath() + 
						 ": file updated\n");
				try
				{
					rewrite(so);
				}
				catch(IOException e)
				{
					slog.log(Level.WARNING, so.getAbsolutePath() 
							+ " - error rewrite file");
				}
			}
			else 
			{
				slog.log(Level.INFO, this.getAbsolutePath() 
						+ ": source file old\n");
			}
		}
	}
	
	/**
	 * Rewrite this file to so
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public void rewrite(File so) throws IOException, FileNotFoundException
	{
		if(so.exists()){
			so.delete();
		}
		so.createNewFile();
		FileOutputStream out = new FileOutputStream(so);
		FileInputStream in = new FileInputStream(currentFile);
		long i = 0;
		while(i < in.getChannel().size()){
			out.write(in.read());
			i++;
		}
		
		out.close();
		in.close();
	}
}
